// Copyright (C) 1998-2008, Sumisho Computer Systems Corp. All Rights Reserved.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @author Hitoshi Okada
 */

package com.curlap.orb.util;

import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.curlap.orb.io.SerializableStreamWriter;
import com.curlap.orb.io.SerializerException;

/**
 * TextFileStreamWriter
 */
public class TextFileStreamWriter 
{
    private static String DEFAULT_CHARSET = "UTF8";

    // write 
    public static void write(String url, String charset, SerializableStreamWriter writer) throws IOException
    {
        BufferedReader reader = null;
        try 
        {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(url), charset));
            String line = null;
            while((line = reader.readLine()) != null)
                writer.write(line);
        }
        catch (FileNotFoundException e)
        {
            throw new IOException(e.getMessage());
        }
        catch (SerializerException e)
        {
            throw new IOException(e.getMessage());
        }
        finally
        {
            if (writer != null)
            {
                try
                {
                    writer.close();
                }
                catch (SerializerException e)
                {
                    throw new IOException(e.getMessage());
                }
            }
            if (reader != null)
                reader.close();
        }
    }

    // write as UTF8
    public static void write(String url, SerializableStreamWriter writer) throws IOException
    {
        write(url, DEFAULT_CHARSET, writer);
    }
}
